package com.atguigu.guli.service.sms.controller;


import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.common.base.result.ResultCodeEnum;
import com.atguigu.guli.common.base.util.FormUtils;
import com.atguigu.guli.common.base.util.RandomUtils;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.sms.client.CoreUserInfoClient;
import com.atguigu.guli.service.sms.service.SmsService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin //跨域
@Slf4j
public class ApiSmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate redisTemplate;

    /*@Resource
    private CoreUserInfoClient coreUserInfoClient;*/

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号",required = true)
            @PathVariable String mobile){

        //校验手机号码不能为空,校验手机号码的合法性
        if(StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)) {
            log.error("请输入正确的手机号码 ");
            throw new GuliException(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }



        //判断手机号是否已经注册

//        boolean result = coreUserInfoClient.checkMobile(mobile);
//        System.out.println("result = " + result);
//        Assert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);

        //生成验证码
        String checkCode = RandomUtils.getFourBitRandom();

        //发送短信
        //R send = smsService.send(mobile, checkCode);

        // 将验证码存入redis
        redisTemplate.opsForValue().set(mobile,checkCode,5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
        //return send;
    }
}
